﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ePlanet.ArchiveMange.Services;
using ePlanet.ArchiveMange.Models;
using DreamBuilder.Core.Container;
using Microsoft.Practices.Unity;
using Web.SystemConfig.Services;
using ePlanet.SingleWell.Services;
using CommonModule;
using ePlanet.SingleWell.Models;
using System.Data;
using ePlanet.ArchiveMange.Enum;

namespace Web.Views.ArchiveView
{
    public partial class ViewPageFile : ArchiveFlowEditPageBase
    {
        #region 属性变量
        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }


        [Dependency]
        public IAuth_Org orgService
        {
            get;
            set;
        }

        public string archiveTypeName;

        /// <summary>
        /// 卷内件ID
        /// </summary>
        public string DataID
        {
            get
            {
                if (Request.QueryString["DataID"] != null)
                {
                    ViewState["DataID"] = Request.QueryString["DataID"];
                }
                if (ViewState["DataID"] != null)
                {
                    return ViewState["DataID"].ToString();
                }
                else
                {
                    ViewState["DataID"] = Guid.NewGuid().ToString();
                    return ViewState["DataID"].ToString();
                }
            }
        }

        /// <summary>
        /// 卷ID
        /// </summary>
        public string ArchiveId
        {
            get
            {
                if (Request.QueryString["archiveId"] != null)
                {
                    ViewState["archiveId"] = Request.QueryString["archiveId"];
                }
                if (ViewState["archiveId"] != null)
                {
                    return ViewState["archiveId"].ToString();
                }
                else
                {
                    ViewState["archiveId"] = Guid.NewGuid().ToString();
                    return ViewState["archiveId"].ToString();
                }
            }
        }
        /// <summary>
        /// 档案类型
        /// </summary>
        public string ReqArchiveType
        {
            get
            {
                if (this.Request.QueryString["archiveType"] != null)
                {
                    return this.Request.QueryString["archiveType"];
                }
                else
                {
                    throw new Exception("档案类型不能为空");
                }
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitControls();
                LoadData();
                BindGrid();
            }
            SetControlVisable();
            archiveTypeName = this.h_archiveTypeName.Value;
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            IPageFileService DocumentArchiveService = UContainer.Resolve<IPageFileService>();
            ArchiveMangeModal.PAGEFILEDataTable dt = DocumentArchiveService.GetAllDocumenArchivetDataById(this.DataID);
            if (dt.Rows.Count > 0)
            {
                this.CurrentPageState = PageState.State_Edit;

                ArchiveMangeModal.PAGEFILERow row = dt.Rows[0] as ArchiveMangeModal.PAGEFILERow;
                this.txtArchiveNum.Text = row.ARCHIVENUM;
                this.txtArchiveSource.Text = row.ARCHIVESOURCE;
                ArchiveMangeModal.ARCHIVEMENUDataTable dtMenu = ArchiveMenuService.GetArchiveMenuById(row.ARCHIVETYPE.ToString());
                ArchiveMangeModal.ARCHIVEMENURow drMenu = dtMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow;
                this.txtArchiveType.Text = drMenu.ARCHIVEMENU;
                this.h_ArchiveTypeId.Value = row.ARCHIVETYPE.ToString();
                this.txtBoxNum.Text = row.BOXNUM;
                //DataTable dtOrg = orgService.GetORGInfo(row.FILEORGID);
                //this.txtFileOrgName.Text = dtOrg.Rows[0]["Org_Name"].ToString();
                //this.h_FileOrgID.Value = row.FILEORGID;
                //归档单位改为直接明文了
                this.txtFileOrgName.Text = row.FILEORGID;
                this.txtFullFondsNum.Text = row.FULLFONDSNUM;
                this.txtPageNum.Text = row.PAGENUM.ToString();
                this.txtPublishTime.Text = row.IsPUBLISHTIMENull() ? "" : row.PUBLISHTIME.ToString("yyyy-MM-dd");
                this.txtTempOrderNum.Text = row.TEMPORDERNUM;
                this.txtTitle.Text = row.TITLE;
                this.ddlCarrierType.SelectedValue = row.F_CARRIERTYPE;
                this.ddlKeepTime.SelectedValue = row.F_KEEPTIME;
                this.ddlSecurity.SelectedValue = row.F_SECURITYTYPE;

                //对卷内件不同的值进行处理-----------------------------
                this.txtPublisher.Text = row.PUBLISHER;//责任者，除会计类之外都有
                this.txtDocumentNum.Text = row.DOCUMENTNUM;//文件编号，科研类特有
                this.txtHujianhao.Text = row.HUJIANHAO;//互见号，科研类特有
                this.txtTypeNum.Text = row.TYPENUM;//型号，设备类特有
                this.ddlYear.Text = row.F_YEAR;//年度，会计类特有

                this.ddlKeepSecurityTime.SelectedValue = row.F_KEEPSECURITYTIME;
            }
        }

        /// <summary>
        /// 初始化数据项
        /// </summary>
        private void InitControls()
        {
            //初始化附件上传控件
            DataSet KeepTime = CodeTableService.GetCodeTableDataByType("KeepTime");
            if (KeepTime != null && KeepTime.Tables.Count > 0)
            {
                this.ddlKeepTime.DataSource = KeepTime;
                this.ddlKeepTime.DataTextField = "Code_Desc";
                this.ddlKeepTime.DataValueField = "CodeTableID";
                this.ddlKeepTime.DataBind();
                this.ddlKeepTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            DataSet CarrierType = CodeTableService.GetCodeTableDataByType("CarrierType");
            if (CarrierType != null && CarrierType.Tables.Count > 0)
            {
                this.ddlCarrierType.DataSource = CarrierType;
                this.ddlCarrierType.DataTextField = "Code_Desc";
                this.ddlCarrierType.DataValueField = "CodeTableID";
                this.ddlCarrierType.DataBind();
                this.ddlCarrierType.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            DataSet SecurityData = CodeTableService.GetCodeTableDataByType("SecurityType");
            if (SecurityData != null && SecurityData.Tables.Count > 0)
            {
                this.ddlSecurity.DataSource = SecurityData;
                this.ddlSecurity.DataTextField = "Code_Desc";
                this.ddlSecurity.DataValueField = "CodeTableID";
                this.ddlSecurity.DataBind();
                this.ddlSecurity.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }
            //保密期限ddlKeepSecurityTime
            DataSet KeepSecurityTimeData = CodeTableService.GetCodeTableDataByType("KeepSecurityTime");
            if (KeepSecurityTimeData != null && KeepSecurityTimeData.Tables.Count > 0)
            {
                this.ddlKeepSecurityTime.DataSource = KeepSecurityTimeData;
                this.ddlKeepSecurityTime.DataTextField = "Code_Desc";
                this.ddlKeepSecurityTime.DataValueField = "CodeTableID";
                this.ddlKeepSecurityTime.DataBind();
                this.ddlKeepSecurityTime.Items.Insert(0, new ListItem("--请选择--", "-1"));
            }

            //年度（会计类特有）
            //int year = DateTime.Now.Year;
            //for (int i = year - 10; i < year + 10; i++)
            //{
            //    this.ddlYear.Items.Add(new ListItem("--" + i + "--", i.ToString()));
            //}
            //this.ddlYear.Items.Insert(0, new ListItem("--请选择--", "-1"));

            ArchiveMangeModal.ARCHIVEMENUDataTable dtArchiveMenu = ArchiveMenuService.GetArchiveMenuById(ReqArchiveType);
            ArchiveMangeModal.ARCHIVEMENURow row = (dtArchiveMenu.Rows[0] as ArchiveMangeModal.ARCHIVEMENURow);
            if (dtArchiveMenu != null && dtArchiveMenu.Rows.Count > 0)
            {
                this.txtArchiveType.Text = row.TYPECODE;
                this.h_ArchiveTypeId.Value = row.TYPEID.ToString();
                this.h_archiveTypeName.Value = row.ARCHIVEMENU;
            }
            //来源
            this.txtArchiveSource.Text = "在线录入__档案整理";
            this.txtFileOrgName.Text = this.CurrentUser.Org_Name;
            //this.txtArchiveNum.Text = ArchiveNum;
            this.txtBoxNum.Text = "未装盒";
            this.txtFullFondsNum.Text = this.CurrentUser.Org_FullFondsNum;
            this.h_FileOrgID.Value = this.CurrentUser.ORG_ID;

            this.txtArchiveNum.Enabled = false;
            this.txtArchiveSource.Enabled = false;
            this.txtFullFondsNum.Enabled = false;
            this.txtArchiveType.Enabled = false;

            this.h_ArchiveTypeId.Value = ReqArchiveType;
            //如果是修改，保存并录入不显示
        }


        /// <summary>
        /// 设置输入控件的可见性
        /// </summary>
        private void SetControlVisable()
        {
            int type = -1;
            if (!int.TryParse(this.ReqArchiveType, out type))
            {
                Alert("档案类型有误");
            }
            int baseType = ArchiveMenuService.GetArchiveBaseIDById(type);
            switch (baseType)
            {
                //如果是科研类
                case ((int)ArchiveBaseType.Technology):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = true;
                    DivDocumentNum.Visible = true;
                    break;
                //如果是设备类
                case ((int)ArchiveBaseType.Equipment):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = true;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
                //如果是基建类
                case ((int)ArchiveBaseType.BulidProject):
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = true;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = true;
                    break;
                //如果是会计类
                case ((int)ArchiveBaseType.Account):
                    DivYear.Visible = true;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = false;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
                //默认，全部都隐藏
                default:
                    DivYear.Visible = false;
                    DivTypeNum.Visible = false;
                    DivPubLisher.Visible = false;
                    DivHujianhao.Visible = false;
                    DivDocumentNum.Visible = false;
                    break;
            }

        }

        private void BindGrid()
        {
            //AttachmentDAL attach = UContainer.Resolve<AttachmentDAL>();
            //attach.AttachmentDBHelperString = "PageFile";
            //DataTable dtAttach= attach.GetAttachmentList(DataID, null, null, null, null);
            //this.gv_Attach.DataSource = dtAttach;
            //this.gv_Attach.DataBind();

            IAttachmentService jnjIAttachmentService = UContainer.Resolve<IAttachmentService>();
            jnjIAttachmentService.Initialize(AttachDbHelperString.PageFile);
            List<AttachmentModel> jnjAttachments = jnjIAttachmentService.GetAttachmentModelByObjectID(new List<string> { DataID });
            DataTable attachDataTable = null;
            this.TransAttachmentModelListToDataTable(out attachDataTable, jnjAttachments, AttachDbHelperString.PageFile);
            this.gv_Attach.DataSource = attachDataTable;
            this.gv_Attach.DataBind();
        }

        /// <summary>
        /// 转换附件数据类型
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="attachments"></param>
        private void TransAttachmentModelListToDataTable(out DataTable dataTable, List<AttachmentModel> attachments, string DBHelperString)
        {
            dataTable = new DataTable();
            if (attachments != null && attachments.Count > 0)
            {
                dataTable.Columns.Add("attachmentid");
                dataTable.Columns.Add("AttachmentName");
                dataTable.Columns.Add("UpdateTime");
                dataTable.Columns.Add("AttachmentSize");
                dataTable.Columns.Add("DBHelperString");
                dataTable.Columns.Add("uploadtime");
                dataTable.Columns.Add("documenttype");

                foreach (AttachmentModel model in attachments)
                {
                    DataRow newRow = dataTable.NewRow();
                    newRow["attachmentid"] = model.AttachmentID;
                    newRow["AttachmentName"] = model.AttachmentName;
                    newRow["UpdateTime"] = model.UpdateTime.ToShortDateString();
                    newRow["AttachmentSize"] = (model.AttachmentSize / ((float)(1024 * 1024))).ToString() + "M";
                    newRow["uploadtime"] = model.UpdateTime.ToShortDateString();
                    newRow["DBHelperString"] = DBHelperString;
                    newRow["documenttype"] = model.DocumentType;

                    dataTable.Rows.Add(newRow);
                }
            }
        }

        protected void gv_Attach_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                //浏览
                if (OP.Equals("scan") || OP.Equals("fromdatamgr"))
                {
                    string fileExt = row["documenttype"] == null ? "" : row["documenttype"].ToString().ToLower();
                    if (fileExt.Equals("jpg") || fileExt.Equals("bmp") || fileExt.Equals("png"))
                    {
                        e.Row.Cells[2].Text = string.Format("<a target='_blank' href='../../ImageCutAndPrint.aspx?mode=fromserver&DBHelperString=PageFile&AttachmentId={0}'>{1}</a>",
                        row["attachmentid"], row["attachmentname"]);
                    }
                    else
                    {
                        e.Row.Cells[2].Text = string.Format("<a target='_blank' href='../../WebDoc/WebDoc.aspx?AttachmentID={0}&AttachmentDBHelperString={2}'>{1}</a>",
                        row["attachmentid"], row["attachmentname"], row["DBHelperString"]);
                    }
                    
                }
            }
        }
    }
}